package cn.cuilan.controller;

import cn.cuilan.entity.User;
import cn.cuilan.service.UserService;
import cn.cuilan.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户Controller
 *
 * @author zhang.yan
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登陆
     *
     * @param userName 手机号或邮箱
     * @param password 密码
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Results login(
            @RequestParam("username") String userName,
            @RequestParam("password") String password,
            HttpServletResponse response) {
        // json跨域支持
        response.setHeader("Access-Control-Allow-Origin", "*");
        Results results = new Results();
        // 验证参数是否为空
        if (Validate.isNullParam(userName, password)) {
            return Results.error().result(ErrorCode.PARAM_IS_NULL);
        }
        // 登录
        User user = userService.login(userName);
        // MD5加密密码
        password = EncodeUtils.md5(password);
        // 数据库中是否有该用户、密码是否正确
        if (user == null || user.getId() <= 0 || !user.getPassword().equals(password)) {
            return Results.error().result(ErrorCode.USER_UNEXSIT);
        }
        // 加密信息并生成token
        String token = TokenHandler.createToken(
                user.getId(),
                user.getUserName(),
                user.getPassword());
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("user", user);
        returnMap.put("token", token);
        // 返回
        return Results.success().data(returnMap);
    }

    /**
     * 根据id获取用户信息
     *
     * @param id userId
     * @return 返回用户对象
     */
    @RequestMapping(value = "/getUserById", method = RequestMethod.GET)
    public Results getUserById(long id) {
        User user = userService.getById(id);
        return Results.success().data(user);
    }

}
